<template>
  <div>
    <!-- -------------------新增角色表单-------------------- -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesFormVisible"
      width="50%"
      @close="addRolesFormClose"
    >
      <!-- form主体内容 -->
      <el-form
        :model="addRolesForm"
        :rules="addRolesFormRules"
        ref="addRolesFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" size="small" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" :rows="5" v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- form底部按钮 -->
      <span slot="footer">
        <el-button @click="addRolesFormVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitAddRolesForm" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addRolesFormVisible: true,
      // 数据绑定
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // 验证规则
      addRolesFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 16,
            message: "长度在 1 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {},
  methods: {
    //监听关闭添加角色form
    addRolesFormClose() {
      this.addRolesFormVisible = false;
      this.$router.replace("/Roles");
    },
    // 提交新增角色表单加预验证功能
    submitAddRolesForm() {
      this.$refs.addRolesFormRef.validate((valid) => {
        if (valid) {
          this.$axios
            .post("roles", this.addRolesForm)
            .then((res) => {
              if (res.data.meta.status == 201) {
                this.$message.success("新增角色成功");
                // 向父组件传递刷新数据
                this.$emit("refreshData",true)
              } else {
                this.$message.error("新增角色失败");
              }
              this.addRolesFormVisible = false;
            })
            .catch((error) => {
              console.log(error); //cathch用于处理错误事件
            });
        } else {
          this.$message.error("预校验失败");
          return;
        }
      });
    },
  },
};
</script>

<style scoped>
</style>

